<template>
  <el-dialog :model-value="props.dialogVisible" @update:model-value="handleClose" title="请登录" width="500">
    <el-form :model="form">
      <el-form-item label="用户名:" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户名"
          type="username"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          type="password"
          style="width: 240px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit"> 登录 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref,defineProps,defineEmits, reactive } from "vue";
import  request  from "@/components/utiles/request.js";
import {useAuthStore} from "@/stores/authStore";
import { ElMessage } from "element-plus";
const authStore = useAuthStore();
const form = reactive({
  username: "",
  password: "",
});
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits<{
  (e: 'update:dialogVisible', value: boolean): void;
}>();
// 关闭对话框时通知父组件
const handleClose = () => {
  emit('update:dialogVisible', false);
};
const submit = async() => {
    if (!form.username || !form.password) {
        alert("用户名和密码不能为空");
        return;
    }
    // 提交表单
    const res = await request.post("/user/login", form);
    if (res.data.code === 200) {
        // 登录成功，保存 token
        authStore.setToken(res.data.data);
        ElMessage.success("登录成功");
    } else {
        // 登录失败，提示错误信息
        ElMessage.error(res.data.message);
    }
    // 这里可以添加登录逻辑，比如发送请求到后端进行验证
    // 如果登录成功，关闭对话框
    handleClose();
};
</script>
